package com.cdtye.itps.cms.service.datasysn;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdtye.common.kafkacore.model.attr.ConsumerErrorAttr;
import com.cdtye.common.kafkacore.model.entity.KfkConsumerError;
import com.cdtye.common.kafkacore.model.entity.KfkConsumerRecord;
import com.cdtye.common.kafkacore.model.entity.KfkConsumerRule;
import com.cdtye.common.kafkacore.model.enums.KfkErrorFieldTypeEnum;
import com.cdtye.common.kafkacore.model.enums.KfkErrorTypeEnum;
import com.cdtye.common.kafkacore.service.KfkConsumerErrorService;
import com.cdtye.common.kafkacore.service.KfkConsumerRecordService;
import com.cdtye.common.kafkacore.service.KfkConsumerRuleService;
import com.cdtye.common.webcore.enums.YesNoEnum;
import com.cdtye.common.webcore.util.DateUtil;
import com.cdtye.itps.cms.dao.datasysn.C124DetectJob;
import com.cdtye.itps.cms.dao.datasysn.Defect;
import com.cdtye.itps.cms.dao.datasysn.DetailPlanOriginal;
import com.cdtye.itps.cms.dao.defect.entity.JcwDefectInfoPhoto;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectCategory;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectInfo;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectLevel;
import com.cdtye.itps.cms.dao.dept.entity.SysDept;
import com.cdtye.itps.cms.dao.detect.JcjcDefectInfoSection;
import com.cdtye.itps.cms.dao.detect.JcjcDefectSourceTypeSection;
import com.cdtye.itps.cms.dao.detect.JcjcDefectTypeSection;
import com.cdtye.itps.cms.dao.direction.entity.JcDirection;
import com.cdtye.itps.cms.dao.line.entity.DelectJcSecline;
import com.cdtye.itps.cms.dao.lineSite.entity.JcLineSite;
import com.cdtye.itps.cms.dao.origindata.entity.JcjcDetectC1Job;
import com.cdtye.itps.cms.dao.origindata.entity.JcjcDetectC2Job;
import com.cdtye.itps.cms.dao.origindata.entity.JcjcDetectC4Job;
import com.cdtye.itps.cms.dao.pillar.entity.JcwPillar;
import com.cdtye.itps.cms.dao.plan.entity.JcjcPlanDetail;
import com.cdtye.itps.cms.service.defect.JcjcDefectTypeSectionService;
import com.cdtye.itps.cms.service.defect.JcwProblemDefectCategoryService;
import com.cdtye.itps.cms.service.defect.JcwProblemDefectLevelService;
import com.cdtye.itps.cms.service.origindata.*;
import com.cdtye.itps.cms.service.pillar.JcwPillarService;
import com.cdtye.itps.cms.service.plan.JcjcPlanDetailService;
import com.cdtye.itps.models.base.model.attr.basic.*;
import com.cdtye.itps.models.base.model.attr.defect.DefectGatherTypeAttr;
import com.cdtye.itps.models.base.model.attr.defect.DefectGradeAttr;
import com.cdtye.itps.models.base.model.attr.defect.DefectPhotoAttr;
import com.cdtye.itps.models.base.model.attr.detect.DetectDeviceAttr;
import com.cdtye.itps.models.base.model.attr.sysm.DeptAttr;
import com.cdtye.itps.models.base.model.entity.basic.Pillar;
import com.cdtye.itps.models.base.model.entity.defect.*;
import com.cdtye.itps.models.base.model.entity.detect.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;

import java.util.*;

import org.springframework.util.CollectionUtils;


@Slf4j
@Service
public class PlanDetailService{


    @Autowired
    private KfkConsumerErrorService kfkConsumerErrorService;
    @Autowired
    private KfkConsumerRecordService kfkConsumerRecordService;
    @Autowired
    JcjcHandleService jcjcHandleService;
    @Autowired
    private PreHandleService preHandleService;
    @Autowired
    private KfkConsumerRuleService kfkConsumerRuleService;
    @Autowired
    private JcwPillarService jcwPillarService;
    @Autowired
    JcjcPlanDetailService jcjcPlanDetailService;
    @Autowired
    JcjcDetectC1JobService jcjcDetectC1JobService;
    @Autowired
    JcjcDetectC2JobService jcjcDetectC2JobService;
    @Autowired
    JcjcDetectC4JobService jcjcDetectC4JobService;
    @Autowired
    JcjcDetectC1DataService jcjcDetectC1DataService;
    @Autowired
    JcjcDetectC2IndexService jcjcDetectC2IndexService;
    @Autowired
    JcjcDetectC4IndexService jcjcDetectC4IndexService;
    @Autowired
    JcjcDetectC4PictureService jcjcDetectC4PictureService;
    @Autowired
    private JcwProblemDefectCategoryService JcwProblemDefectCategoryService;
    @Autowired
    private JcwProblemDefectLevelService jcwProblemDefectLevelService;
    @Autowired
    private JcjcDefectTypeSectionService jcjcDefectTypeSectionService;


    @Value("${detect.roadMark.multiple:1000}")
    private Long multiple;

    public final static Map<String, String> CTYPE = new HashMap<String, String>() {
        {
            put("1", "JCJCTYPE01");
            put("2", "JCJCTYPE02");
            put("3", "JCJCTYPE03");
            put("4", "JCJCTYPE04");
            put("5", "JCJCTYPE05");
//            put("6C", "JCJCTYPE06");
        }
    };

    /**
     * 处理检测计划数据
     * 验证线路和行别
     *
     * @param record
     */
    public void savePlanDetailService(ConsumerRecord record) throws Exception {
        //获取基础数据进行验证
        log.info("开始预处理[检测计划数据]");
        List<DetailPlanOriginal> dpList = JSON.parseArray(record.value().toString(), DetailPlanOriginal.class);
        log.info("检测计划数据为："+dpList.size());
        if (CollectionUtils.isEmpty(dpList)) {
            return;
        }
        Map<String, SysDept> deptMap = jcjcHandleService.findDeptsMap(record.key().toString());
        Map<String, DelectJcSecline> lineMap = jcjcHandleService.findLinesMap(record.key().toString());
        Map<String, JcLineSite> lineSiteMap = jcjcHandleService.findLineSitesMap(record.key().toString());
        Map<String, JcDirection> directionMap = jcjcHandleService.findDirectionsMap(record.key().toString());

        //消费总条数，成功条数、失败数量(处理次数超过1将不统计，并且处理成功后将减1)
        int consumerNum = dpList.size(), successNum = 0, errorNum = 0;

        //获取发送记录ID
        String producerId = dpList.get(0).getProducerId();
        KfkConsumerRecord kcrModel = new KfkConsumerRecord(record, producerId);
        List<JcjcPlanDetail> jpdList = new ArrayList<>();
        for (DetailPlanOriginal dp : dpList) {
            JcjcPlanDetail jcjcPlanDetail = dp.covEntity();
            List<ConsumerErrorAttr> errorList = new ArrayList<>();
            //基础数据预处理
            //1、处理部门
            DeptAttr deptAttr = new DeptAttr();
            deptAttr.setDeptCode(dp.getPowerSupplySectionCode());
            deptAttr.setDeptName(dp.getPowerSupplySectionName());
            //部门验证改成 查询映射表
            //Object preObj = jcjcHandleService.checkDept(deptMap, deptAttr, record.key().toString());
            Object preObj = jcjcHandleService.checkDeptInfo(deptAttr);
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
            } else {
                SysDept sysDept = (SysDept)preObj;
                jcjcPlanDetail.setDeptId(sysDept.getDeptId());
            }

            //2、处理执行部门
            deptAttr.setDeptCode(dp.getExecuteDeptCode());
            deptAttr.setDeptName(dp.getExecuteDeptName());
            //部门验证改成 查询映射表
            //preObj = jcjcHandleService.checkDept(deptMap, deptAttr, record.key().toString());
            preObj = jcjcHandleService.checkDeptInfo(deptAttr);
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
            } else {
                SysDept sysDept = (SysDept)preObj;
                jcjcPlanDetail.setPlanDepartmentId(sysDept.getDeptId());
            }

            //3、处理线路
            LineAttr lineAttr = new LineAttr();
            lineAttr.setLineCode(dp.getLineCode());
            lineAttr.setLineName(dp.getLineName());
            preObj = jcjcHandleService.checkLine(lineMap, lineAttr, record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
            } else {
                DelectJcSecline line = (DelectJcSecline) preObj;
                jcjcPlanDetail.setLineId(line.getLineId());
            }

            //4、处理行别
            DirectionAttr directionAttr = new DirectionAttr();
            directionAttr.setDirectionCode(dp.getLineTypeCode());
            directionAttr.setDirectionName(dp.getLineTypeName());
            preObj = jcjcHandleService.checkDirection(directionMap, directionAttr,record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
            } else {
                JcDirection direction = (JcDirection) preObj;
                jcjcPlanDetail.setDirectionId(direction.getDirectionId());
            }

            //5、处理计划起站
            SiteAttr siteAttr = new SiteAttr();
            siteAttr.setSiteName(dp.getStartStName());
            siteAttr.setLineSiteCode(dp.getStartStCode());
            preObj = jcjcHandleService.checkSite(lineSiteMap, siteAttr, dp.getLineName(),jcjcPlanDetail.getLineId(), record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
            } else {
                JcLineSite jcjcLineSite = (JcLineSite) preObj;
                jcjcPlanDetail.setLineSitePlanBeginId(jcjcLineSite.getSiteId());
            }

            //6、处理计划止站
            siteAttr.setSiteName(dp.getEndStName());
            siteAttr.setLineSiteCode(dp.getEndStCode());
            preObj = jcjcHandleService.checkSite(lineSiteMap, siteAttr, dp.getLineName(),jcjcPlanDetail.getLineId(), record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
            } else {
                JcLineSite jcjcLineSite = (JcLineSite) preObj;
                jcjcPlanDetail.setLineSitePlanEndId(jcjcLineSite.getSiteId());
            }

            //7、处理实际起站
            siteAttr.setSiteName(dp.getRealStartStName());
            siteAttr.setLineSiteCode(dp.getRealStartStCode());
            preObj = jcjcHandleService.checkSite(lineSiteMap, siteAttr, dp.getLineName(),jcjcPlanDetail.getLineId(), record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
            } else {
                JcLineSite jcjcLineSite = (JcLineSite) preObj;
                jcjcPlanDetail.setLineSiteActualBeginId(jcjcLineSite.getSiteId());
            }

            //8、处理实际止站
            siteAttr.setSiteName(dp.getRealEndStName());
            siteAttr.setLineSiteCode(dp.getRealEndStCode());
            preObj = jcjcHandleService.checkSite(lineSiteMap, siteAttr, dp.getLineName(),jcjcPlanDetail.getLineId(), record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
            } else {
                JcLineSite jcjcLineSite = (JcLineSite) preObj;
                jcjcPlanDetail.setLineSiteActualEndId(jcjcLineSite.getSiteId());
            }


            //判断预处理是否通过。通过：保存数据，不通过保存异常数据
            if (CollectionUtils.isEmpty(errorList)) {
                //保存数据。更新时间必须重新赋值，否则同步会出问题
                //判断oracle中是否有此缺陷信息，有就更新，没有插入
                QueryWrapper<JcjcPlanDetail> planDetailWrapper = new QueryWrapper<>();
                planDetailWrapper.eq("EXT_PLAN_ID",jcjcPlanDetail.getExtPlanId());
                JcjcPlanDetail planDetail = jcjcPlanDetailService.getOne(planDetailWrapper);
                if (planDetail == null) {//新增
                    jcjcPlanDetailService.save(jcjcPlanDetail);
                }else {//修改
                    jcjcPlanDetail.setId(planDetail.getId());
                    jcjcPlanDetailService.update(jcjcPlanDetail,planDetailWrapper);
                }
            } else {
                //保存预处理未通过
                KfkConsumerError errorModel = new KfkConsumerError(record, kcrModel.getId(), producerId)
                        .setErrorData(dp).setConsumerErrorList(errorList);
                //设置collClazzName，后续校正的时候会用到
                errorModel.setCollClazzName("com.cdtye.itps.cms.dao.detect.JcjcPlanDetailMongo");
                kfkConsumerErrorService.insert(errorModel);
                errorNum++;
            }
        }

        //保存消费记录
        kfkConsumerRecordService.saveByHandle(kcrModel, consumerNum, successNum, errorNum);
        preHandleService.saveMonitorLog("Detect-->saveConsumerDefect", consumerNum, successNum);

    }


    //处理朔黄
    /**
     * 处理检测缺陷数据
     * 验证线路和行别
     * @param record
     */
    public void saveShuoHuangDetailService(ConsumerRecord record) throws Exception {

        //获取基础数据进行验证
        log.info("朔黄---开始预处理[6C-检测缺陷]----------record.key=" + record.key().toString());
        List<Defect> dtoList = JSON.parseArray(record.value().toString(), Defect.class);
        if (CollectionUtils.isEmpty(dtoList)) {
            return;
        }
        //获取发送记录ID
        if(dtoList.size()==0 || dtoList.get(0) ==null){
            return;
        }

        Map<String, SysDept> deptMap = jcjcHandleService.findDeptsMap(record.key().toString());
        Map<String, DelectJcSecline> lineMap = jcjcHandleService.findLinesMap(record.key().toString());
        Map<String, JcLineSite> lineSiteMap = jcjcHandleService.findLineSitesMap(record.key().toString());
        Map<String, JcDirection> directionMap = jcjcHandleService.findDirectionsMap(record.key().toString());
        JcjcDefectSourceTypeSection defectSourceType = jcjcHandleService.findDefectSourceTypeId(record.key().toString());

        //消费总条数，成功条数、失败数量(处理次数超过1将不统计，并且处理成功后将减1)
        int consumerNum = dtoList.size(), successNum = 0, errorNum = 0;

        String producerId = dtoList.get(0).getProducerId();
        KfkConsumerRecord kcrModel = new KfkConsumerRecord(record, producerId);
        //接触网缺陷信息表oracle数据库实体类，段级(插入)
        for (Defect dto : dtoList) {
            //把所有属性标准化，attr或list需要手动转换
            JcwDefectInfo model = dto.covEntity();
            model.setDataSysnKey(record.key().toString());
            model.setDataSysnFlag("1");//未同步
            JcwProblemDefectInfo jcwProblemDefectInfo = new JcwProblemDefectInfo();
//            JcjcDefectInfoSection jcjcDefectInfoSection = new JcjcDefectInfoSection();
//            JcjcDefectInfoSection jcjcDefectInfo = new JcjcDefectInfoSection();

            List<ConsumerErrorAttr> errorList = new ArrayList<>();
            //处理公里标除以1000
            if (model.getRoadMark() != null) {
                model.setRoadMark(model.getRoadMark() / multiple);
            }

            //基础数据预处理
            //1、处理部门
            if(model.getDeptAttr().getDeptName() == null){
                DeptAttr deptAttr = new DeptAttr();
                if(StringUtils.isBlank(dto.getWorkAreaCode())){
                    if(StringUtils.isBlank(dto.getWorkShopCode())){
                        deptAttr.setDeptCode(dto.getPowerSupplySectionCode());
                        deptAttr.setDeptName(dto.getPowerSupplySectionName());
                    }else{
                        deptAttr.setDeptCode(dto.getWorkShopCode());
                        deptAttr.setDeptName(dto.getWorkShopName());
                    }
                }else{
                    deptAttr.setDeptCode(dto.getWorkAreaCode());
                    deptAttr.setDeptName(dto.getWorkAreaName());
                }
                model.setDeptAttr(deptAttr);
            }

            Object preObj = jcjcHandleService.checkDeptInfo(model.getDeptAttr());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
                log.info("朔黄---部门1:::::");
            } else {
                SysDept sysDept = (SysDept)preObj;
                model.setDeptAttr(sysDept.getDeptAttr());
                jcwProblemDefectInfo.setFindDeptId(sysDept.getDeptId());
                jcwProblemDefectInfo.setDeptCode(sysDept.getDeptNo());
                jcwProblemDefectInfo.setUnitDeptCode(sysDept.getUnitDeptCode());
//                jcjcDefectInfoSection.setDeptId(sysDept.getDeptId());
//                jcjcDefectInfoSection.setFindDeptId(sysDept.getDeptId());
                //必须挂接部门
                if (StringUtils.isBlank(model.getDeptAttr().getDeptCode())) {
                    errorList.add(jcjcHandleService.getDeptErrorAttr(null, "该记录未挂接部门"));
                    log.info("朔黄---部门2:::::");
                }
            }
            //2、处理线路
            preObj = jcjcHandleService.checkLine(lineMap, model.getLineAttr(), record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
                log.info("朔黄---线路1:::::");
            } else {
                DelectJcSecline jcjcSecline = (DelectJcSecline) preObj;
                model.setLineAttr(jcjcSecline.getLineAttr());
                jcwProblemDefectInfo.setLineId(jcjcSecline.getSeclineId());
//                jcjcDefectInfoSection.setSeclineId(jcjcSecline.getSeclineId());
                //必须挂接线路
                if (StringUtils.isBlank(model.getLineAttr().getLineId())) {
                    errorList.add(jcjcHandleService.getLineErrorAttr(null, "该记录未挂接线路"));
                    log.info("朔黄---线路2:::::");
                }
            }
            //3、处理区站
            preObj = jcjcHandleService.checkSite(lineSiteMap, model.getSiteAttr(), dto.getLineName(), model.getLineAttr().getLineId(), record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
                log.info("朔黄---区站1:::::");
            } else {
                JcLineSite jcjcLineSite = (JcLineSite) preObj;
                model.getSiteAttr().setSiteId(jcjcLineSite.getSiteId()).setLineId(jcjcLineSite.getSeclineId());
                jcwProblemDefectInfo.setLineSiteId(jcjcLineSite.getSiteId());
//                jcjcDefectInfoSection.setSiteId(jcjcLineSite.getSiteId());
                //必须挂接区站
                if (StringUtils.isBlank(model.getSiteAttr().getSiteId())) {
                    errorList.add(jcjcHandleService.getSiteErrorAttr(null, "该记录未挂接区站"));
                    log.info("朔黄---区站2:::::");

                }
            }
            //4、处理行别
            preObj = jcjcHandleService.checkDirection(directionMap, model.getDirectionAttr(), record.key().toString());
            if (preObj instanceof ConsumerErrorAttr) {
                errorList.add((ConsumerErrorAttr) preObj);
                log.info("朔黄---行别1:::::");
            } else {
                JcDirection jcjcDirectionOriginal = (JcDirection) preObj;
                model.getDirectionAttr().setDirectionId(jcjcDirectionOriginal.getDirectionId()).setDirectionName(jcjcDirectionOriginal.getDirectionName());
                jcwProblemDefectInfo.setDirectionId(jcjcDirectionOriginal.getDirectionId());
//                jcjcDefectInfoSection.setDirectionId(jcjcDirectionOriginal.getDirectionId());
                if (dto.getLineName() != null && dto.getStName() != null) {
                    String errorCode = jcjcDirectionOriginal.getDirectionId() + "_" + dto.getLineName() + "_" + dto.getStName();
                    KfkConsumerRule kfkConsumerRule = kfkConsumerRuleService.findByTypeCode(KfkErrorTypeEnum.DIRECTION.getType(), errorCode, record.key().toString());
                    if (kfkConsumerRule != null) {
                        JcDirection jcjcDirection = directionMap.get(JSON.parseObject(JSON.toJSONString(kfkConsumerRule.getData()), DirectionAttr.class).getDirectionName());
                        model.getDirectionAttr().setDirectionId(jcjcDirection.getDirectionId()).setDirectionName(jcjcDirection.getDirectionName());
                        jcwProblemDefectInfo.setDirectionId(jcjcDirection.getDirectionId());
//                        jcjcDefectInfoSection.setDirectionId(jcjcDirectionOriginal.getDirectionId());
                    }
                    //必须挂接行别
                    if (StringUtils.isBlank(model.getDirectionAttr().getDirectionCode())) {
                        errorList.add(jcjcHandleService.getDirectionErrorAttr(null, "该记录未挂接行别"));
                        log.info("朔黄---行别2:::::");
                    }
                }
            }
            //5、处理隧道
            //6、处理支柱
            //通过段级id查询局级支柱表，得到局级支柱对象
            if(model.getPillarAttr().getPillarNum() != null){
                List<JcwPillar> jcwPillar = jcwPillarService.findPillarByPillarlNum(model.getPillarAttr().getPillarNum(), jcwProblemDefectInfo.getLineId(), dto.getLineDirectCode(), jcwProblemDefectInfo.getLineSiteId());
                if (jcwPillar.size() != 0) {
                    log.info("朔黄---支柱:::::"+jcwPillar);
                    jcwProblemDefectInfo.setPillarId(jcwPillar.get(0).getPillarId());
                    jcwProblemDefectInfo.setPillarNum(jcwPillar.get(0).getPillarNum());
                    jcwProblemDefectInfo.setPillarDeptId(jcwPillar.get(0).getDeptId());
                    jcwProblemDefectInfo.setRoadMark(jcwPillar.get(0).getRoadMark());
//                    jcjcDefectInfoSection.setPillarId(jcwPillar.get(0).getPillarId());
//                    jcjcDefectInfoSection.setPillarNum(jcwPillar.get(0).getPillarNum());
//                    jcjcDefectInfoSection.setPillarDeptId(jcwPillar.get(0).getDeptId());
//                    jcjcDefectInfoSection.setRoadMark(jcwPillar.get(0).getRoadMark());
                } else {
                    errorList.add(jcjcHandleService.getPillarErrorAttr(model.getPillarAttr().getPillarCode(), "支柱不存在"));
                    log.info("朔黄---支柱1:::::");
                }
            }
            //7 缺陷分类
            List<JcwProblemDefectCategory> categoryList = JcwProblemDefectCategoryService.findDefectCategory(dto.getTypeName(), dto.getTypeCode());
            if (categoryList != null && categoryList.size() == 1) {
                jcwProblemDefectInfo.setDefectCategoryId(categoryList.get(0).getId());
            } else {
                errorList.add(jcjcHandleService.getUserDefectTypeErrorAttr(model.getDefectClass().getDicId(), "用户缺陷分类不存在"));
                log.info("朔黄---分类:::::");
            }

            //8 缺陷等级
            JcwProblemDefectLevel jcwProblemDefectLevel = jcwProblemDefectLevelService.findOneByLevelName(model.getGradeAttr().getUserGradeName());
//            jcjcDefectInfoSection.setDefectGradeId(dto.getFaultLevelCode());
            if (jcwProblemDefectLevel != null) {
                jcwProblemDefectInfo.setDefectLevelId(jcwProblemDefectLevel.getId());
            } else {
                ConsumerErrorAttr consumerErrorAttrLevel =  new ConsumerErrorAttr().setErrorType(KfkErrorTypeEnum.DEFECT_GRADE.getType())
                        .setErrorCode(model.getGradeAttr().getGradeCode()).setErrorReason("用户缺陷分类不存在")
                        .setErrorField("defectGradeAttr").setErrorFieldType(KfkErrorFieldTypeEnum.OBJECT.getType())
                        .setErrorClazzName(DefectGradeAttr.class.getName()).setStatus(YesNoEnum.NO.getCode());
                errorList.add(consumerErrorAttrLevel);
                log.info("朔黄---等级:::::");
            }
            //TODO:设置股道
            DefectGatherTypeAttr defectGatherTypeAttr = new DefectGatherTypeAttr();
            //1、检修 2、巡视 3、检测，4、检验，5、其它
            defectGatherTypeAttr.setTypeClass(3);
            defectGatherTypeAttr.setCType(dto.getCtype());
            model.setGatherTypeAttr(defectGatherTypeAttr);
            DetectDeviceAttr detectDeviceAttr = new DetectDeviceAttr();
            detectDeviceAttr.setCType(dto.getCtype());
            model.setDetectDeviceAttr(detectDeviceAttr);

            //TODO 设置不需要处理的属性
            //设置段
//            dto.getJcjcDefectInfoSection(jcjcDefectInfoSection);
//            List<JcjcDefectTypeSection> jcjcDefectTypeSection = jcjcDefectTypeSectionService.findOneByDefectType(dto.getTypeName());
//            if (jcjcDefectTypeSection.size() != 0){
//                jcjcDefectInfoSection.setDefectTypeId(jcjcDefectTypeSection.get(0).getDefectTypeId());
//            }

            //设置局
            jcwProblemDefectInfo = dto.getJcwProblemDefectInfo(jcwProblemDefectInfo);
            //ctype设备分类名称
            jcwProblemDefectInfo.setSystemSource("6C");
            jcwProblemDefectInfo.setMistake(3);
            if (defectSourceType != null){
                jcwProblemDefectInfo.setDiscoverSourceId(defectSourceType.getSourceTypeId());
            }
            jcwProblemDefectInfo.setCType(dto.getCtype());
            jcwProblemDefectInfo.setCtypeId(CTYPE.get(dto.getCtype()));

            jcwProblemDefectInfo.setSysnStatus("0");

            //判断预处理是否通过。通过：保存数据，不通过保存异常数据

            log.info("数量:::::"+errorList.size());
            log.info("缺陷:::::"+jcwProblemDefectInfo);
            if (CollectionUtils.isEmpty(errorList)) {
                //保存数据。更新时间必须重新赋值，否则同步会出问题
                model.setUpdateTime(new Date());
                jcwProblemDefectInfo.setDefectStatus(dto.getStatus().toString());
                jcwProblemDefectInfo.setUpdateDatetime(DateUtil.getDateTime());
                //判断oracle中是否有此缺陷信息，有就更新，没有插入
                //校验局完成
                List<JcwProblemDefectInfo> listBureau = jcjcHandleService.selectIdBureauProblemDefectInfo(jcwProblemDefectInfo);
                jcwProblemDefectInfo.setCreateBy("BCA");
                jcwProblemDefectInfo.setUpdateBy("BCA");
                if (CollectionUtils.isEmpty(listBureau)) {//新增
                    jcwProblemDefectInfo.setCreateDatetime(DateUtil.getDateTime());
                    int b = jcjcHandleService.insertBureauProblemDefectInfo(jcwProblemDefectInfo);
                    if (b == 1) {
                        //处理图片
                        if (dto.getPicList() != null){
                            List<JcwDefectInfoPhoto> jdipList = new ArrayList<>();
                            for (DefectPhotoAttr dpa:dto.getPicList()) {
                                jdipList.add(new JcwDefectInfoPhoto()
                                        .setDefectInfoId(jcwProblemDefectInfo.getId())
                                        .setFileName(dpa.getFileName())
                                        .setFilePath(dpa.getFilePath())
                                        .setDefectStage(dpa.getDefectStage())
                                        .setPhotoFlag("3")
                                        .setFileType("1"));
                            }
                            jcjcHandleService.insertDefectInfoPhotoBureau(jdipList);
                        }
                    }
                } else {//修改
                    JcwProblemDefectInfo problemDefectInfo = listBureau.get(0);
                    jcwProblemDefectInfo.setId(problemDefectInfo.getId());
                    jcwProblemDefectInfo.setCreateBy("getDefectInfosHandlerJdgm");
                    jcwProblemDefectInfo.setUpdateBy("getDefectInfosHandlerJdgm");
                    jcjcHandleService.updateBureauProblemDefectInfo(jcwProblemDefectInfo);
                }


                //校验段完成
//                List<JcjcDefectInfoSection> listSection = jcjcHandleService.selectIdSectionProblemDefectInfo(jcjcDefectInfoSection);
//                if (CollectionUtils.isEmpty(listSection)) {//新增
//                    jcjcDefectInfoSection.setCreateDatetime(DateUtil.getDateTime());
//                    int b = jcjcHandleService.insertSectionProblemDefectInfo(jcjcDefectInfoSection);
//                    if (b == 1) {
//                        //处理图片
//                        if (dto.getPicList() != null){
//                            List<JcwDefectInfoPhoto> jdipList = new ArrayList<>();
//                            for (DefectPhotoAttr dpa:dto.getPicList()) {
//                                jdipList.add(new JcwDefectInfoPhoto()
//                                        .setDefectInfoId(jcjcDefectInfoSection.getDefectInfoId())
//                                        .setFileName(dpa.getFileName())
//                                        .setFilePath(dpa.getFilePath())
//                                        .setDefectStage(dpa.getDefectStage())
//                                        .setPhotoFlag("3")
//                                        .setFileType("1"));
//                            }
//                            jcjcHandleService.insertDefectInfoPhotoBureau(jdipList);
//                        }
//                    }
//                } else {//修改
//                    JcjcDefectInfoSection problemDefectInfo = listSection.get(0);
//                    jcjcDefectInfoSection.setDefectInfoId(problemDefectInfo.getDefectInfoId());
//                    jcjcDefectInfoSection.setUpdateDatetime(DateUtil.getDateTime());
//                    jcjcHandleService.updateSectionProblemDefectInfo(jcjcDefectInfoSection);
//                }

                successNum++;
            } else {
                //保存预处理未通过
                KfkConsumerError errorModel = new KfkConsumerError(record, kcrModel.getId(), producerId)
                        .setErrorData(model).setConsumerErrorList(errorList);
                kfkConsumerErrorService.insert(errorModel);
                errorNum++;
            }
        }
        //保存消费记录
        kfkConsumerRecordService.saveByHandle(kcrModel, consumerNum, successNum, errorNum);
        preHandleService.saveMonitorLog("Detect-->saveConsumerDefect", consumerNum, successNum);
    }

    /**
     * 处理1C、2C、4C文件包数据获取 作业
     * 验证线路和行别
     * @param record
     */
    public void saveConsumerC124DetectJob(ConsumerRecord record) throws Exception {
        log.info("开始预处理[1C、2C、4C文件包数据获取-检测作业]");
        List<C124DetectJob> dtoList = JSON.parseArray(record.value().toString(), C124DetectJob.class);
        //List<C124DetectJob> dtoList = (List<C124DetectJob>)record.value();
        if (CollectionUtils.isEmpty(dtoList)) {
            return;
        }
        //获取基础数据进行验证

        Map<String, DelectJcSecline> lineMap = jcjcHandleService.findLinesMap(record.key().toString());
        Map<String, JcLineSite> lineSiteMap = jcjcHandleService.findLineSitesMap(record.key().toString());
        Map<String, JcDirection> directionMap = jcjcHandleService.findDirectionsMap(record.key().toString());

        //消费总条数，成功条数、失败数量(处理次数超过1将不统计，并且处理成功后将减1)
        int consumerNum = dtoList.size(), successNum = 0, errorNum = 0;
        //获取发送记录ID
        String producerId = dtoList.get(0).getProducerId();
        KfkConsumerRecord kcrModel = new KfkConsumerRecord(record, producerId);
        for (C124DetectJob dto : dtoList) {
            List<ConsumerErrorAttr> errorList = new ArrayList<>();
            Map rsMap = dto.covEntity();
            if("1".equals(dto.getType())){
                JcjcDetectC1Job jcjcDetectC1Job = (JcjcDetectC1Job)rsMap.get("detectCxJob");
                jcjcDetectC1Job.setMemo("CBA");
                JcwDetectC1Job model = (JcwDetectC1Job)rsMap.get("model");
                //基础数据预处理验证
                //1、处理线路
                Object preObj = jcjcHandleService.checkLine(lineMap, model.getLineAttr(), record.key().toString());
                if (preObj instanceof ConsumerErrorAttr) {
                    errorList.add((ConsumerErrorAttr) preObj);
                } else {
                    DelectJcSecline jcjcSecline = (DelectJcSecline) preObj;
                    model.setLineAttr(jcjcSecline.getLineAttr());
                    jcjcDetectC1Job.setLineId(jcjcSecline.getLineId());
                    //必须挂接线路
                    if (StringUtils.isBlank(model.getLineAttr().getLineId())) {
                        errorList.add(jcjcHandleService.getLineErrorAttr(null, "该记录未挂接线路"));
                    }
                }
                //2、处理行别
                preObj = jcjcHandleService.checkDirection(directionMap, model.getDirectionAttr(), record.key().toString());
                if (preObj instanceof ConsumerErrorAttr) {
                    errorList.add((ConsumerErrorAttr) preObj);
                } else {
                    JcDirection jcDirectionBureau = (JcDirection) preObj;
                    DirectionAttr directionAttr = new DirectionAttr();
                    directionAttr.setDirectionId(jcDirectionBureau.getDirectionId());
                    directionAttr.setDirectionCode(jcDirectionBureau.getMCode());
                    directionAttr.setDirectionName(jcDirectionBureau.getDirectionName());
                    model.setDirectionAttr(directionAttr);
                    jcjcDetectC1Job.setDirectionId(jcDirectionBureau.getDirectionId());
                    //必须挂接行别
                    if (StringUtils.isBlank(model.getDirectionAttr().getDirectionCode())) {
                        errorList.add(jcjcHandleService.getDirectionErrorAttr(null, "该记录未挂接行别"));
                    }
                }
                //以下不做验证，只获取
                //model.setDetectDeviceAttr(preHandleService.getDetectDevice(model.getDetectDeviceAttr(), record.key().toString()));
                SiteAttr beginSite =preHandleService.getSite2(lineSiteMap, model.getBeginSiteAttr(), model.getLineAttr());
                if(beginSite != null){
                    model.setBeginSiteAttr(beginSite);
                    jcjcDetectC1Job.setBeginSiteId(beginSite.getSiteId());
                }
                SiteAttr endSite = preHandleService.getSite2(lineSiteMap, model.getEndSiteAttr(), model.getLineAttr());
                if(endSite != null){
                    model.setEndSiteAttr(endSite);
                    jcjcDetectC1Job.setEndSiteId(endSite.getSiteId());
                }
                //判断预处理是否通过。通过：保存数据，不通过保存异常数据
                if (CollectionUtils.isEmpty(errorList)) {
                    //保存数据
                    jcjcDetectC1JobService.insertJcjcDetectC1Job(jcjcDetectC1Job);
                    successNum++;
                } else {
                    //保存预处理未通过
                    KfkConsumerError errorModel = new KfkConsumerError(record, kcrModel.getId(), producerId)
                            .setErrorData(model).setConsumerErrorList(errorList);
                    kfkConsumerErrorService.insert(errorModel);
                    errorNum++;
                }
            }else if("2".equals(dto.getType())){
                JcjcDetectC2Job jcjcDetectC2Job = (JcjcDetectC2Job)rsMap.get("detectCxJob");
                jcjcDetectC2Job.setMemo("CBA");
                JcwDetectC2Job model = (JcwDetectC2Job)rsMap.get("model");
                //基础数据预处理验证
                //1、处理线路

                Object preObj = jcjcHandleService.checkLine(lineMap, model.getLineAttr(), record.key().toString());
                if (preObj instanceof ConsumerErrorAttr) {
                    errorList.add((ConsumerErrorAttr) preObj);
                } else {
                    DelectJcSecline jcjcSecline = (DelectJcSecline) preObj;
                    model.setLineAttr(jcjcSecline.getLineAttr());
                    jcjcDetectC2Job.setLineId(jcjcSecline.getLineId());
                    //必须挂接线路
                    if (StringUtils.isBlank(model.getLineAttr().getLineId())) {
                        errorList.add(jcjcHandleService.getLineErrorAttr(null, "该记录未挂接线路"));
                    }
                }
                //2、处理行别
                preObj = jcjcHandleService.checkDirection(directionMap, model.getDirectionAttr(), record.key().toString());
                if (preObj instanceof ConsumerErrorAttr) {
                    errorList.add((ConsumerErrorAttr) preObj);
                } else {
                    JcDirection jcDirection = (JcDirection) preObj;
                    DirectionAttr directionAttr = new DirectionAttr();
                    directionAttr.setDirectionId(jcDirection.getDirectionId());
                    directionAttr.setDirectionCode(jcDirection.getMCode());
                    directionAttr.setDirectionName(jcDirection.getDirectionName());
                    model.setDirectionAttr(directionAttr);
                    jcjcDetectC2Job.setDirectionId(jcDirection.getDirectionId());
                    //必须挂接行别
                    if (StringUtils.isBlank(model.getDirectionAttr().getDirectionCode())) {
                        errorList.add(jcjcHandleService.getDirectionErrorAttr(null, "该记录未挂接行别"));
                    }
                }
                //以下不做验证、只获取
                //model.setDetectDeviceAttr(preHandleService.getDetectDevice(model.getDetectDeviceAttr(), record.key().toString()));
                SiteAttr beginSite = preHandleService.getSite2(lineSiteMap, model.getBeginSiteAttr(), model.getLineAttr());
                if(beginSite != null){
                    model.setBeginSiteAttr(beginSite);
                    jcjcDetectC2Job.setBeginSiteId(beginSite.getSiteId());
                }
                SiteAttr endSite = preHandleService.getSite2(lineSiteMap, model.getEndSiteAttr(), model.getLineAttr());
                if(endSite != null){
                    model.setEndSiteAttr(endSite);
                    jcjcDetectC2Job.setEndSiteId(endSite.getSiteId());
                }
                Pillar beginPillar = preHandleService.getPillar(model.getBeginPillarAttr(), model.getLineAttr()
                        , model.getBeginSiteAttr(), model.getDirectionAttr(), null, null, record.key().toString());
                if(beginPillar != null && beginPillar.getId() != null){
                    PillarAttr pillarAttr = new PillarAttr(beginPillar);
                    model.setBeginPillarAttr(pillarAttr);
                    jcjcDetectC2Job.setBeginPillarNo(beginPillar.getPillarNum());
                }
                Pillar endPillar = preHandleService.getPillar(model.getEndPillarAttr(), model.getLineAttr()
                        , model.getEndSiteAttr(), model.getDirectionAttr(), null, null, record.key().toString());
                if(endPillar != null && endPillar.getId() != null){
                    PillarAttr pillarAttr = new PillarAttr(endPillar);
                    model.setEndPillarAttr(pillarAttr);
                    jcjcDetectC2Job.setEndPillarNo(endPillar.getPillarNum());
                }

                //处理依赖检测作业ID相关的异常数据
                //kfkConsumerErrorService.updateAndSendError(KfkErrorTypeEnum.JCW_DETECT_JOB.getType(), model.getId());
                //判断预处理是否通过。通过：保存数据，不通过保存异常数据
                if (CollectionUtils.isEmpty(errorList)) {
                    //保存数据
                    jcjcDetectC2JobService.insertJcjcDetectC2Job(jcjcDetectC2Job);
                    successNum++;
                } else {
                    //保存预处理未通过
                    KfkConsumerError errorModel = new KfkConsumerError(record, kcrModel.getId(), producerId)
                            .setErrorData(model).setConsumerErrorList(errorList);
                    kfkConsumerErrorService.insert(errorModel);
                    errorNum++;
                }
            }else if("4".equals(dto.getType())){
                JcjcDetectC4Job jcjcDetectC4Job = (JcjcDetectC4Job)rsMap.get("detectCxJob");
                jcjcDetectC4Job.setMemo("CBA");
                JcwDetectC4Job model = (JcwDetectC4Job)rsMap.get("model");
                //基础数据预处理验证
                //1、处理线路
                Object preObj = jcjcHandleService.checkLine(lineMap, model.getLineAttr(), record.key().toString());
                if (preObj instanceof ConsumerErrorAttr) {
                    errorList.add((ConsumerErrorAttr) preObj);
                } else {
                    DelectJcSecline jcjcSecline = (DelectJcSecline) preObj;
                    model.setLineAttr(jcjcSecline.getLineAttr());
                    jcjcDetectC4Job.setLineId(jcjcSecline.getLineId());
                    //必须挂接线路
                    if (StringUtils.isBlank(model.getLineAttr().getLineId())) {
                        errorList.add(jcjcHandleService.getLineErrorAttr(null, "该记录未挂接线路"));
                    }
                }
                //2、处理行别
                preObj = jcjcHandleService.checkDirection(directionMap, model.getDirectionAttr(), record.key().toString());
                if (preObj instanceof ConsumerErrorAttr) {
                    errorList.add((ConsumerErrorAttr) preObj);
                } else {
                    JcDirection jcDirection = (JcDirection) preObj;
                    DirectionAttr directionAttr = new DirectionAttr();
                    directionAttr.setDirectionId(jcDirection.getDirectionId());
                    directionAttr.setDirectionCode(jcDirection.getMCode());
                    directionAttr.setDirectionName(jcDirection.getDirectionName());
                    model.setDirectionAttr(directionAttr);
                    jcjcDetectC4Job.setDirectionId(jcDirection.getDirectionId());
                    //必须挂接行别
                    if (StringUtils.isBlank(model.getDirectionAttr().getDirectionCode())) {
                        errorList.add(jcjcHandleService.getDirectionErrorAttr(null, "该记录未挂接行别"));
                    }
                }
                //以下不做验证，只获取
                //model.setDetectDeviceAttr(preHandleService.getDetectDevice(model.getDetectDeviceAttr(), record.key().toString()));
                SiteAttr beginSite = preHandleService.getSite2(lineSiteMap, model.getBeginSiteAttr(), model.getLineAttr());
                if(beginSite != null){
                    model.setBeginSiteAttr(beginSite);
                    jcjcDetectC4Job.setBeginSiteId(beginSite.getSiteId());
                }
                SiteAttr endSite = preHandleService.getSite2(lineSiteMap, model.getEndSiteAttr(), model.getLineAttr());
                if(endSite != null){
                    model.setEndSiteAttr(endSite);
                    jcjcDetectC4Job.setEndSiteId(endSite.getSiteId());
                }


                model.setStartPillarAttr(new PillarAttr(preHandleService.getPillar(model.getStartPillarAttr(), model.getLineAttr()
                        , model.getBeginSiteAttr(), model.getDirectionAttr(), null, null, record.key().toString())));
                model.setEndPillarAttr(new PillarAttr(preHandleService.getPillar(model.getEndPillarAttr(), model.getLineAttr()
                        , model.getEndSiteAttr(), model.getDirectionAttr(), null, null, record.key().toString())));

                Pillar beginPillar = preHandleService.getPillar(model.getStartPillarAttr(), model.getLineAttr()
                        , model.getBeginSiteAttr(), model.getDirectionAttr(), null, null, record.key().toString());
                if(beginPillar != null && beginPillar.getId() != null){
                    PillarAttr pillarAttr = new PillarAttr(beginPillar);
                    model.setStartPillarAttr(pillarAttr);
                    jcjcDetectC4Job.setStartPillarId(beginPillar.getId());
                }
                Pillar endPillar = preHandleService.getPillar(model.getEndPillarAttr(), model.getLineAttr()
                        , model.getEndSiteAttr(), model.getDirectionAttr(), null, null, record.key().toString());
                if(endPillar != null && endPillar.getId() != null){
                    PillarAttr pillarAttr = new PillarAttr(endPillar);
                    model.setEndPillarAttr(pillarAttr);
                    jcjcDetectC4Job.setEndPillarId(endPillar.getId());
                }
                //判断预处理是否通过。通过：保存数据，不通过保存异常数据
                if (CollectionUtils.isEmpty(errorList)) {
                    //保存数据
                    jcjcDetectC4JobService.insertJcjcDetectC4Job(jcjcDetectC4Job);
                    successNum++;
                } else {
                    //保存预处理未通过
                    KfkConsumerError errorModel = new KfkConsumerError(record, kcrModel.getId(), producerId)
                            .setErrorData(model).setConsumerErrorList(errorList);
                    kfkConsumerErrorService.insert(errorModel);
                    errorNum++;
                }
            }

        }
        //保存消费记录
        kfkConsumerRecordService.saveByHandle(kcrModel, consumerNum, successNum, errorNum);
        preHandleService.saveMonitorLog("Detect-->saveConsumerC124DetectJob", consumerNum, successNum);
    }

}
